package org.zxw.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.zxw.service.VideoAnalysisService;
import org.zxw.utils.AliOss;
import org.zxw.utils.HttpClientUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class VideoAnalysisServiceImpl implements VideoAnalysisService {
    @Value("${python.service.url}")
    private String pythonServiceUrl;

    private AliOss oss;

    private String urlName = "/analyze";
    private String videoName = "video_url";

    public VideoAnalysisServiceImpl(AliOss oss) {
        this.oss = oss;
    }
    
    /**
     * 视频动作解析
     * 1. 上传视频到OSS
     * 2. 获取视频URL
     * 3. 调用Python服务进行分析
     * 4. 返回分析结果
     */
    public String analyzeVideo(MultipartFile video) throws IOException {
        // 1. 上传视频到OSS
        String objectName = oss.uploadVideoToOss(video);
        
        // 2. 生成视频的访问URL
        String videoUrl = oss.generateUrl(objectName);
        log.info("Video uploaded to OSS, accessible at: {}", videoUrl);
        
        // 3. 调用Python服务进行分析
        return callPythonAnalysisService(videoUrl);
    }

    
    /**
     * 调用Python分析服务
     */
    private String callPythonAnalysisService(String videoUrl) {
        String url = pythonServiceUrl + urlName;
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put(videoName, videoUrl);
        try {
            String entity = HttpClientUtil.doPost4Json(url, paramMap);
            return entity;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}